﻿using System.Linq;
using System.Threading.Tasks;
using Devonline.Core;
using Devonline.Http;
using Devonline.Identity.Admin.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Devonline.Identity.Admin.Controllers
{
    /// <summary>
    /// 组织部门管理
    /// </summary>    
    [Route("api/[controller]")]
    [SecurityHeaders]
    [ApiController]
    [Authorize(Roles = AppSettings.GROUP_MAINTAINERS)]
    public class GroupsController : ControllerBase
    {
        private readonly IdentityDbContext _context;
        private readonly ILogger<GroupsController> _logger;

        public GroupsController(
            IdentityDbContext context,
            ILogger<GroupsController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 查询组织单位
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [EnableQuery]
        public IActionResult Get()
        {
            _logger.LogInformation("user {user} query the group list", User.Identity.Name);
            return Ok(_context.Groups);
        }

        /// <summary>
        /// 创建组织单位
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateAsync(GroupViewModel viewModel)
        {
            _logger.LogInformation("user {user} will add the group {group}", User.Identity.Name, viewModel.Name);
            if (await _context.Groups.AnyAsync(x => x.Name == viewModel.Name))
            {
                return BadRequest($"组织单位 {viewModel.Name} 已经存在!");
            }

            var group = new Group
            {
                Name = viewModel.Name,
                Alias = viewModel.Alias,
                Image = viewModel.Image,
                Type = viewModel.Type,
                ParentId = viewModel.ParentId,
                Description = viewModel.Description
            };

            group.Create(User.Identity.Name);
            group.Update(User.Identity.Name);
            _context.Groups.Add(group);

            //处理新增附件
            await _context.AddAttachmentsAsync(group, viewModel.Attachments);
            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to add the group {group}", User.Identity.Name, group.Name);
                return Ok();
            }

            return BadRequest($"创建组织单位 {viewModel.Name} 没有成功!");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> ChangeAsync(string id, GroupViewModel viewModel)
        {
            _logger.LogInformation("user {user} will change the group {group}", User.Identity.Name, id);
            var group = await _context.Groups.FindAsync(id);
            if (group == null)
            {
                return NotFound();
            }

            viewModel.CopyTo(group);

            //处理附件, 无附件则不用写下面的代码及删除文件的代码
            var files = await _context.UpdateAttachmentsAsync(group, viewModel.Attachments);
            if (files.IsNotNullOrEmpty() && files.Any(x => x == group.Image))
            {
                group.Image = null;
            }

            group.Update(User.Identity.Name);
            _context.Groups.Update(group);

            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to change the group {group}", User.Identity.Name, group.Name);
                files.Delete(_logger);
                return Ok();
            }

            return BadRequest($"修改组织单位 {viewModel.Name} 没有成功!");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAsync(string id)
        {
            _logger.LogInformation("user {user} will delete the group {group}", User.Identity.Name, id);
            var group = await _context.Groups.FindAsync(id);
            if (group == null)
            {
                return NotFound();
            }

            //处理附件, 无附件则不用写下面的代码及删除文件的代码
            var files = await _context.DeleteAttachmentsAsync(id);

            _context.Groups.Remove(group);
            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to delete the group {group}", User.Identity.Name, group.Name);
                files.Delete(_logger);
                return Ok();
            }

            return BadRequest($"删除组织单位 {group.Name} 出错!");
        }
    }
}
